package sm.hibernate.type;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;

import sm.codec.type.NullValue;
import sm.codec.type.RC;
import sm.codec.type.Struct;

public class CLobCharacterType extends AbstractPrimitiveType {

	@Override
	public int[] sqlTypes() {
		return new int[] { Types.CLOB };
	}

	@Override
	public Class returnedClass() {
		return String.class;
	}

	@Override
	public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
			throws HibernateException, SQLException {
		Object value = Hibernate.TEXT.nullSafeGet(rs, names);
		if (value == null) {
			value = NullValue.CharacterNull;
		} else {
			value = RCTypeHelper.dbStringToJava(value);
		}
		return value;
	}

	@Override
	public void nullSafeSet(PreparedStatement st, Object value, int index)
			throws HibernateException, SQLException {
		if (value instanceof NullValue || value instanceof RC
				|| value instanceof Struct) {
			value = null;
		}

		if (value != null) {
			value = RCTypeHelper.javaStringToDB(value.toString());
		}

		Hibernate.TEXT.nullSafeSet(st, value, index);

	}

}
